package com.epoch.base.schedule;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;

import com.epoch.base.constant.Constant;
import com.epoch.platform.sys.job.dao.SysScheduleJob;
import com.jfinal.plugin.IPlugin;

public class QuartzPlugin implements IPlugin {

    public boolean start() {
        try {
            Scheduler scheduler = QuartzKit.getSchedulerFactory().getScheduler();
            scheduler.start();
            this.startPropertiesJobs();
            return true;
        } catch (Exception var3) {
            throw new RuntimeException("Can\'t start quartz plugin.", var3);
        }
    }

    public boolean stop() {
        try {
            QuartzKit.getSchedulerFactory().getScheduler().shutdown();
            QuartzKit.setSchedulerFactory((SchedulerFactory) null);
            return true;
        } catch (Exception var2) {
            throw new RuntimeException("Can\'t stop quartz plugin.", var2);
        }
    }

    public void startPropertiesJobs() {
        //从数据库中读取任务
        List<SysScheduleJob> sysScheduleJob = SysScheduleJob.dao.find("select * from sys_schedule_job where job_status='" + Constant.JOB_STATUS_0 + "'");
        if (CollectionUtils.isEmpty(sysScheduleJob)) {
            //LoggerUtil.getLogger().info("-##当前没有定时任务");
            return;
        }

        for (SysScheduleJob scheduleJob : sysScheduleJob) {
            TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getStr(SysScheduleJob.JOB_NAME), scheduleJob.getStr(SysScheduleJob.JOB_GROUP));
            try {
                Scheduler scheduler = QuartzKit.getSchedulerFactory().getScheduler();
                CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
                if (Constant.JOB_STATUS_0.equals(scheduleJob.getStr(SysScheduleJob.JOB_STATUS))) {
                    // 不存在，创建一个
                    if (null == trigger) {
                        JobDetail jobDetail = JobBuilder.newJob(
                                (Class<? extends Job>) Class.forName(scheduleJob.getStr(SysScheduleJob.TARGET_CLASS)).newInstance().getClass())
                                .withIdentity(scheduleJob.getStr(SysScheduleJob.JOB_NAME), scheduleJob.getStr(SysScheduleJob.JOB_GROUP)).build();
                        jobDetail.getJobDataMap().put("scheduleJob", scheduleJob);
                        // 表达式调度构建器
                        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getStr(SysScheduleJob.CRON_EXPRESSION));
                        // 按新的cronExpression表达式构建一个新的trigger
                        trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getStr(SysScheduleJob.JOB_NAME), scheduleJob.getStr(SysScheduleJob.JOB_GROUP))
                                .withSchedule(scheduleBuilder).build();
                        scheduler.scheduleJob(jobDetail, trigger);
                    } else {
                        // Trigger已存在，那么更新相应的定时设置
                        // 表达式调度构建器
                        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getStr(SysScheduleJob.CRON_EXPRESSION));
                        // 按新的cronExpression表达式重新构建trigger
                        trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder)
                                .build();
                        // 按新的trigger重新设置job执行
                        scheduler.rescheduleJob(triggerKey, trigger);
                    }
                } else {
                    scheduleJob.put(SysScheduleJob.JOB_STATUS, Constant.JOB_STATUS_2);
                    scheduleJob.saveOrUpdate();
                }
            } catch (Exception e) {
                //LoggerUtil.getLogger().error(e.getMessage());
            }
        }
    }
}
